interface ShopifyConfig {
  shopDomain: string;
  accessToken: string;
}

export const verifyShopifyConnection = async (config: ShopifyConfig): Promise<boolean> => {
  try {
    const formData = new FormData();
    formData.append('action', 'verifyConnection');
    formData.append('shopDomain', config.shopDomain);
    formData.append('accessToken', config.accessToken);

    const response = await fetch('/api/shopify', {
      method: 'POST',
      body: formData,
    });
    
    const data = await response.json();
    return data.success;
  } catch (error) {
    console.error('Shopify connection verification failed:', error);
    return false;
  }
};

export const getShopifyProducts = async (config: ShopifyConfig) => {
  const response = await fetch('/api/shopify', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      action: 'getProducts',
      config
    }),
  });

  if (!response.ok) {
    throw new Error('Failed to fetch Shopify products');
  }

  const data = await response.json();
  return data.products;
};

export const saveDesignToShopify = async (designData: any, config: ShopifyConfig) => {
  const response = await fetch('/api/shopify', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      action: 'saveDesign',
      designData,
      config
    }),
  });

  if (!response.ok) {
    throw new Error('Failed to save design to Shopify');
  }

  return response.json();
};

export const updateShopifyProductImage = async (productId: string, imageId: string, imageData: string, config: ShopifyConfig) => {
  const response = await fetch('/api/shopify', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      action: 'updateProductImage',
      productId,
      imageId,
      imageData,
      config
    }),
  });

  if (!response.ok) {
    throw new Error('Failed to update Shopify product image');
  }

  return response.json();
};

export const SHOPIFY_CONFIG = {
  shopDomain: process.env.SHOPIFY_SHOP_DOMAIN || '',
  accessToken: process.env.SHOPIFY_ACCESS_TOKEN || ''
}; 